"""
用户账户相关功能：注册、登录、短信、注销
"""
import datetime
import uuid

from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from web.forms.account import RegisterModelForm, SendEmailForm, LoginEmailForm, LoginForm
from web import models
from utils.image_code import check_code


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'web/register.html', {'form': form})
    else:
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():
            # 验证通过，写入数据库（注意密码存入数据库要哈希加密）
            # 可以在这里这样写：form.instance.password = 'xxxx'
            form.save()
            # 用户表中新建一条数据
            # instance = form.save()
            # # 生成一条交易记录
            # models.Transaction.objects.create(
            #     status=2,
            #     order=str(uuid.uuid4()),
            #     user=instance,
            #     price_policy=models.PricePolicy.objects.filter(category=1, title='个人免费版').first(),
            #     count=0,
            #     price=0,
            #     start_datetime=datetime.datetime.now()
            # )
            return JsonResponse({'status': True, 'next': '/web/login/'})

        return JsonResponse({'status': False, 'error': form.errors})


def send_email(request):
    form = SendEmailForm(request, data=request.GET)

    if form.is_valid():
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})

def login_email(request):
    """ 邮箱登录 """
    if request.method == 'GET':
        form = LoginEmailForm()
        return render(request, 'web/login_email.html', {'form': form})
    else:
        form = LoginEmailForm(data=request.POST)
        if form.is_valid():
            # 拿到用户
            user = models.UserInfo.objects.filter(email=form.cleaned_data['email']).first()
            # 写入session
            request.session['user_id'] = user.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return JsonResponse({'status': True, 'next': '/web/index/'})

    return JsonResponse({'status': False, 'error': form.errors})

def login(request):
    """ 用户名和密码登录 """
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})
    else:
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            # print(username, password)
            # print(models.UserInfo.objects.filter(username=username).first())
            user = models.UserInfo.objects.filter(username=username, password=password).first()
            if user:
                request.session['user_id'] = user.id
                request.session.set_expiry(60 * 60 * 24 * 14)
                return JsonResponse({'status': True, 'next': '/web/index/'})
            form.add_error('username', '用户名或密码错误')

    return JsonResponse({'status': False, 'error': form.errors})


def image_code(request):
    """ 生成图片验证码 """
    img, code = check_code()
    # 将图片验证码存入session中
    request.session['image_code'] = code
    # 设置超时时间
    request.session.set_expiry(60)

    # 将图片写到内存中
    from io import BytesIO
    stream = BytesIO()
    img.save(stream, 'png')

    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()  # 将session清空

    # 这里用的是别名
    return redirect('login')